package com.ruoyi.extend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.db.domain.ChannelInfo;
import com.ruoyi.db.domain.CountInfo;
import com.ruoyi.db.mapper.ChannelInfoMapper;
import com.ruoyi.db.mapper.CountInfoMapper;
import com.ruoyi.db.mapper.MemberInfoMapper;
import com.ruoyi.db.model.param.CountInfoParam;
import com.ruoyi.extend.service.ICountInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 渠道统计Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-08-11
 */
@Service
@DataSource(DataSourceType.SLAVE)
public class CountInfoServiceImpl implements ICountInfoService
{
    @Autowired
    private CountInfoMapper countInfoMapper;

    @Autowired
    ChannelInfoMapper channelInfoMapper;


    /**
     * 查询渠道统计
     * 
     * @param id 渠道统计主键
     * @return 渠道统计
     */
    @Override
    public CountInfo selectCountInfoById(String id)
    {
        return countInfoMapper.selectCountInfoById(id);
    }

    /**
     * 查询渠道统计列表
     * 
     * @param countInfo 渠道统计
     * @return 渠道统计
     */
    @Override
    public List<CountInfo> selectCountInfoList(CountInfo countInfo)
    {
        return countInfoMapper.selectCountInfoList(countInfo);
    }

    /**
     * 查询渠道统计列表
     *
     * @return 渠道统计
     */
    @Override
    public List<Map<String, Object>> selectCountInfoListMap(CountInfoParam countInfoParam)
    {
        return countInfoMapper.selectCountInfoListMap(countInfoParam);
    }

    /**
     * 新增渠道统计
     * 
     * @param countInfo 渠道统计
     * @return 结果
     */
    @Override
    public int insertCountInfo(CountInfo countInfo)
    {
        countInfo.setCreateTime(DateUtils.getNowDate());
        return countInfoMapper.insertCountInfo(countInfo);
    }

    /**
     * 修改渠道统计
     * 
     * @param countInfo 渠道统计
     * @return 结果
     */
    @Override
    public int updateCountInfo(CountInfo countInfo)
    {
        countInfo.setUpdateTime(DateUtils.getNowDate());
        return countInfoMapper.updateCountInfo(countInfo);
    }

    /**
     * 批量删除渠道统计
     * 
     * @param ids 需要删除的渠道统计主键
     * @return 结果
     */
    @Override
    public int deleteCountInfoByIds(String ids)
    {
        return countInfoMapper.deleteCountInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除渠道统计信息
     * 
     * @param id 渠道统计主键
     * @return 结果
     */
    @Override
    public int deleteCountInfoById(String id)
    {
        return countInfoMapper.deleteCountInfoById(id);
    }

    @Override
    public Map<String, Object> selectAllCountInfoListMap(CountInfoParam countInfoParam) {
        return countInfoMapper.selectAllCountInfoListMap(countInfoParam);
    }

    @Override
    public Map<String, Object> getTotalCountInfo() {

        LocalDate now = LocalDate.now();
        Map<String, Object> resultMap = countInfoMapper.getTotalCountInfo(now.toString());

        return resultMap;
    }


    /**
     * 查询暴露出去的外部数据信息
     *
     * @param sysUser
     * @param countInfo
     * @return
     */
    @Override
    public List<Map<String, Object>> selectCountInfoOutSideMap(SysUser sysUser, CountInfo countInfo) {

        Long role1 = 107L;
        Long role2 = 108L;

        List<Map<String, Object>> resultList = new ArrayList<>();
        if (this.containsRoleId(sysUser, role1)){
            // 查询渠道绑定的用户ID信息 却为注册计价类型的渠道信息
            ChannelInfo channelInfo = channelInfoMapper.selectChannelInfoByAdminUid(sysUser.getUserId());

            // 查询绑定
            if (ObjectUtil.isNotEmpty(channelInfo)){
                // 绑定的渠道信息不为空，倒序查询该渠道所有的统计信息
                CountInfo queryEntity = new CountInfo();
                queryEntity.setChannelCode(channelInfo.getChannelCode());
                queryEntity.setDateInfo(countInfo.getDateInfo());
                // TODO: 2022/11/18

                List<CountInfo> countInfoList = countInfoMapper.selectCountInfoList(queryEntity);

                resultList = this.countChannelOutSideData(channelInfo, countInfoList);

            }
//        }else if (this.containsRoleId(sysUser, role2)){
        }else{
            // 查询所有 注册类渠道 的信息
            ChannelInfo queryEntity = new ChannelInfo();
            queryEntity.setChargeType(2);// 注册类型
            List<ChannelInfo> channelInfoList = channelInfoMapper.selectChannelInfoList(queryEntity);

            for (ChannelInfo channelInfo: channelInfoList){
                CountInfo queryEntity1 = new CountInfo();
                queryEntity1.setChannelCode(channelInfo.getChannelCode());
                queryEntity1.setDateInfo(countInfo.getDateInfo());
                List<CountInfo> countInfoList = countInfoMapper.selectCountInfoList(queryEntity1);

                List<Map<String, Object>> list = this.countChannelOutSideData(channelInfo, countInfoList);
                resultList.addAll(list);
            }
        }
        return resultList;
    }

    /**
     * 判断是否包含用户角色
     * @param sysUser
     * @param roleId
     * @return
     */
    public boolean containsRoleId(SysUser sysUser, Long roleId){
        List<SysRole> roles = sysUser.getRoles();
        for (SysRole role: roles){
            if (ObjectUtil.equal(role.getRoleId(), roleId)){
                return true;
            }
        }
        return false;
    }


    @Resource
    MemberInfoMapper memberInfoMapper;

    /**
     * 查询渠道的统计数据
     *
     * @param channelInfo
     */
    public List<Map<String, Object>> countChannelOutSideData(ChannelInfo channelInfo, List<CountInfo> countInfoList){

        List<Map<String, Object>> resultList = new ArrayList<>();
        countInfoList.stream().forEach(countInfo1 -> {

            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("channelCode", countInfo1.getChannelCode());
            objectMap.put("channelName", channelInfo.getChannelName());
            objectMap.put("dateInfo", countInfo1.getDateInfo());

            Long realNumber = memberInfoMapper.selectCountRealUser(countInfo1.getDateInfo(), countInfo1.getChannelCode());
//            Long realNumber = numberMap.get(countInfo1.getChannelCode());
            Long registerCount = ObjectUtil.isEmpty(realNumber)?0:realNumber;
            BigDecimal channelRate = countInfo1.getChannelRate();

            BigDecimal bigDecimal = BigDecimal.valueOf(registerCount).multiply(channelRate).setScale(0, RoundingMode.DOWN);

            String nowDate = LocalDate.now().toString();
//            if (StrUtil.equals(nowDate, countInfo1.getDateInfo()) &&
//                    StrUtil.equals("AOCSAX", countInfo1.getChannelCode())){
//                bigDecimal = new BigDecimal("72");
//            }
            objectMap.put("registerCount", bigDecimal);
            objectMap.put("settleCount", bigDecimal);

            resultList.add(objectMap);
        });

        return resultList;
    }

}
